package com.example.taphelper.utils

import android.content.Context
import android.content.SharedPreferences
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import java.text.SimpleDateFormat
import java.util.*

/**
 * 点击历史记录数据类
 */
data class ClickRecord(
    val x: Int,
    val y: Int,
    val timestamp: Long,
    val sessionId: String = "" // 会话ID，用于区分不同的自动点击会话
) {
    fun getFormattedTime(): String {
        val sdf = SimpleDateFormat("MM-dd HH:mm:ss", Locale.getDefault())
        return sdf.format(Date(timestamp))
    }
    
    fun getDetailedInfo(): String {
        return "${getFormattedTime()} - 点击位置: ($x, $y)"
    }
}

/**
 * 点击历史管理器
 */
class ClickHistoryManager(private val context: Context) {
    
    companion object {
        private const val PREFS_NAME = "click_history_prefs"
        private const val KEY_HISTORY = "click_history"
        private const val MAX_HISTORY_SIZE = 500 // 最大记录数量
    }
    
    private val sharedPrefs: SharedPreferences = 
        context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE)
    private val gson = Gson()
    
    /**
     * 添加点击记录
     */
    fun addClickRecord(x: Int, y: Int, sessionId: String = "") {
        val history = getClickHistory().toMutableList()
        val newRecord = ClickRecord(x, y, System.currentTimeMillis(), sessionId)
        
        history.add(0, newRecord) // 添加到列表开头
        
        // 限制历史记录数量
        if (history.size > MAX_HISTORY_SIZE) {
            history.removeAt(history.size - 1)
        }
        
        saveClickHistory(history)
    }
    
    /**
     * 获取点击历史记录
     */
    fun getClickHistory(): List<ClickRecord> {
        val json = sharedPrefs.getString(KEY_HISTORY, "")
        if (json.isNullOrEmpty()) {
            return emptyList()
        }
        
        return try {
            val type = object : TypeToken<List<ClickRecord>>() {}.type
            gson.fromJson(json, type) ?: emptyList()
        } catch (e: Exception) {
            emptyList()
        }
    }
    
    /**
     * 保存点击历史记录
     */
    private fun saveClickHistory(history: List<ClickRecord>) {
        val json = gson.toJson(history)
        sharedPrefs.edit().putString(KEY_HISTORY, json).apply()
    }
    
    /**
     * 清空历史记录
     */
    fun clearHistory() {
        sharedPrefs.edit().remove(KEY_HISTORY).apply()
    }
    
    /**
     * 获取格式化的历史记录文本
     */
    fun getFormattedHistory(): String {
        val history = getClickHistory()
        if (history.isEmpty()) {
            return "暂无点击历史记录"
        }
        
        val sb = StringBuilder()
        sb.append("点击历史记录 (共${history.size}条)\n")
        sb.append("─".repeat(30)).append("\n\n")
        
        var currentSessionId = ""
        var sessionCount = 0
        
        history.forEachIndexed { index, record ->
            // 检查是否为新的会话
            if (record.sessionId.isNotEmpty() && record.sessionId != currentSessionId) {
                currentSessionId = record.sessionId
                sessionCount++
                sb.append("📍 会话 $sessionCount:\n")
            }
            
            sb.append("${index + 1}. ${record.getDetailedInfo()}\n")
            
            // 每10条记录添加分隔线
            if ((index + 1) % 10 == 0 && index < history.size - 1) {
                sb.append("\n").append("─".repeat(20)).append("\n\n")
            }
        }
        
        return sb.toString()
    }
    
    /**
     * 获取统计信息
     */
    fun getStatistics(): String {
        val history = getClickHistory()
        if (history.isEmpty()) {
            return "暂无统计数据"
        }
        
        val totalClicks = history.size
        val uniquePositions = history.map { "${it.x},${it.y}" }.toSet().size
        val sessions = history.filter { it.sessionId.isNotEmpty() }
            .map { it.sessionId }.toSet().size
        
        val firstRecord = history.lastOrNull()
        val lastRecord = history.firstOrNull()
        
        return buildString {
            append("📊 统计信息\n")
            append("─".repeat(20)).append("\n")
            append("总点击次数: $totalClicks\n")
            append("不同位置数: $uniquePositions\n")
            append("会话数量: $sessions\n")
            if (firstRecord != null && lastRecord != null) {
                append("首次记录: ${firstRecord.getFormattedTime()}\n")
                append("最近记录: ${lastRecord.getFormattedTime()}\n")
            }
        }
    }
} 